package com.xuxin.pda.activity;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.zyapi.pos.PosManager;
import android.zyapi.pos.PrinterDevice;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.xuxin.pda.R;
import com.xuxin.pda.adapter.TrashBoxAdapter;
import com.xuxin.pda.base.BaseConstant;
import com.xuxin.pda.base.BasePDAActivity;
import com.xuxin.pda.bean.TrashEnterBean;
import com.xuxin.pda.contract.TrashEnterContract;
import com.xuxin.pda.listener.PrinterListener;
import com.xuxin.pda.popup.ConfirmPopup;
import com.xuxin.pda.presenter.TrashEnterPresenter;
import com.xuxin.pda.utils.ACache;
import com.xuxin.pda.utils.RecycleUtils;

import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2021/2/3 0003
 * 医废入库
 */
public class TrashEnterActivity extends BasePDAActivity implements TrashEnterContract.View {
    private TrashEnterContract.Presenter presenter = new TrashEnterPresenter(this);
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.trash_enter_user)
    TextView trash_enter_user;
    @BindView(R.id.trash_enter_msg)
    TextView trash_enter_msg;
    @BindView(R.id.trash_enter_recycle)
    RecyclerView trash_enter_recycle;

    private TrashBoxAdapter mTrashBoxAdapter;
    private String userName;//用户名
    private String WarehouseId;//库号
    private String InWarehouseTime;//入库时间
    private String userId;//用户id
    private String BoxIds;//多个箱子

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_trash_enter);
    }

    @Override
    public void initView() {
        title_name.setText("医废入库");
        button.setText("确认入库");
        title_right.setVisibility(View.INVISIBLE);
    }

    @Override
    public void initData() {
        initPrint();
        ACache aCache = ACache.get(context);
        userId = aCache.getAsString(BaseConstant.userId);
        userName = aCache.getAsString(BaseConstant.userName);
        trash_enter_user.setText(userName);
        mTrashBoxAdapter = new TrashBoxAdapter();
        RecycleUtils.init(trash_enter_recycle, 4);
        trash_enter_recycle.setAdapter(mTrashBoxAdapter);
    }

    @Override
    public void onComplete() {
        dismiss();
    }

    @Override
    @OnClick({R.id.title_left, R.id.button})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_left) {
            finish();
        } else if (id == R.id.button) {
            WarehouseId = trash_enter_msg.getText().toString();
            BoxIds = StringUtils.join(mTrashBoxAdapter.getData(), ",");
            if (StringUtils.isEmpty(WarehouseId)) {
                ToastUtils.showShort("请扫描库房二维码");
                return;
            }
            if (StringUtils.isEmpty(BoxIds)) {
                ToastUtils.showShort("请扫码添加箱子二维码");
                return;
            }
            new XPopup.Builder(context)
                    .dismissOnTouchOutside(true)
                    .dismissOnBackPressed(true)
                    .asCustom(new ConfirmPopup(context, "确定要入库吗？", new ConfirmPopup.OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            popup.setTitle("正在入库中...").show();
                            handler.sendEmptyMessageDelayed(0, 500);
                        }
                    })).show();
        }
    }

    private String message="";
    private double total = 0;

    @Override
    public void onSuccess(TrashEnterBean enterBean) {
        ToastUtils.showShort("入库成功");
        BoxIds = "";
        mTrashBoxAdapter.setNewInstance(null);
        try {
            List<TrashEnterBean.ResultBean.InfosBean> infoList = enterBean.getResult().get(0).getInfos();
            for (int i = 0; i < infoList.size(); i++) {
                total = total + infoList.get(i).getWeight();
                message = message + infoList.get(i).getCategoryName() + "：" + infoList.get(i).getWeight()+"kg" + "\n";
            }
            String str = String.format(Locale.SIMPLIFIED_CHINESE,"%.2f",total);
            message = "总重量：" + str +"kg"+ "\n" + message;
            print(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        finish();
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                String time = TimeUtils.getNowString();
                presenter.trashEnter(WarehouseId, time, userId, BoxIds);
            }
            return false;
        }
    });

    @Override
    public void onPDASuccess(String message) {
        if (message.startsWith("WHS")) {
            trash_enter_msg.setText(message);
        } else if (message.startsWith("BOX")) {
            if (!mTrashBoxAdapter.getData().contains(message)) {
                mTrashBoxAdapter.addData(message);
            } else {
                ToastUtils.showShort("请勿重复扫码");
            }
        } else {
            ToastUtils.showShort("二维码格式错误");
        }
    }

    /**
     * 初始化打印
     */
    private PrinterDevice mPrinter = null;

    private void initPrint() {
        mPrinter = PosManager.get().getPrinterDevice();
        mPrinter.setPrintEventListener(new PrinterListener());
        mPrinter.init();
    }

    /**
     * 开始打印
     */
    private void print(String message) {
        if (mPrinter.isPrinting()) {
            ToastUtils.showShort("正在打印中，请稍后...");
            return;
        }

        StringBuilder sb = new StringBuilder();
        sb.append("无锡明慈医院");
        sb.append("\n");
        sb.append("(入库汇总)");
        sb.append("\n\n");
        PrinterDevice.TextData title = mPrinter.new TextData();
        mPrinter.addText(25, sb.toString());

        sb = new StringBuilder();
        sb.append("入库人员：").append(userName);
        sb.append("\n");
        sb.append(message);

        sb.append("\n");
        PrinterDevice.TextData tData = mPrinter.new TextData();
        tData.addText(sb.toString());
        mPrinter.addText(25, tData);
        sb = new StringBuilder();

        String time = TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM-dd HH:mm"));
        sb.append("入库时间：").append(time);
        sb.append("\n\n\n\n\n");
        sb.append("\n");
        tData = mPrinter.new TextData();
        tData.addText(sb.toString());
        mPrinter.addText(25, tData);
        mPrinter.printStart();
    }
}